<?php

namespace app\common\validate\tyyh;

class GroupBuying extends Base
{
	/**
     * 验证规则
     */
    protected $rule = [
        'lock'                => 'require',
        'id'                  => 'require',
        'uid'                 => 'require|uid|orderNum',
        'puid'                => 'puid',
        'lv'                  => 'isOptions:GroupBuyingLv'
    ];


    /**
     * 提示消息
     */
    protected $message = [
        'lock.require'                  => '验证规则场景不存在',
        'id.require'                    => '团购用户信息id不能为空',
        'uid.require'                   => '用户ID不能为空',
        'uid.uid'                       => '您已经成为团长',
        'uid.orderNum'                  => '您必须先购买一件商品',
        'puid.puid'                     => '上级必须先成为团长',
        'lv.require'                    => '团长等级不能为空',
        'lv.isOptions'                  => '团长等级不合法'
    ];
    /**
     * 验证场景
     */
    protected $scene = [
        'add'    => ['uid', 'puid', 'lv'],
        'search' => ['lv']
    ];

    //用户是否已经是团长
    protected function uid($value, $rule, $data = []) {
        return !loadModel('tyyh\\GroupBuying')->where(['uid' => $value])->count();
    }

    //上级是否是团长
    protected function puid($value, $rule, $data = []) {
        if($value == 0) {
            return true;
        }
        return !!loadModel('tyyh\\GroupBuying')->where(['uid' => $value])->count();
    }

    //验证用户是否购买商品
    protected function orderNum($value, $rule, $data = []) {
        $user = loadOnly('Model')->find('tyyh\\User', $value);
        return (isset($data['puid']) && $data['puid']) || $user['order_num'] > 0;  
    }
}
